package com.rimi.controller;

import com.rimi.bean.Pets;
import com.rimi.bean.User;
import com.rimi.commons.CommonResult;
import com.rimi.commons.ResultStatus;
import com.rimi.model.vo.PetsAddVo;
import com.rimi.model.dto.PetsListDto;
import com.rimi.service.PetsService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * @author liHaiYang
 * @version V1.0
 * @Description: (用一句话描述该文件做什么)
 * @date 2021/7/6 10:44
 */
@RestController
@CrossOrigin
@Api(description = "宠物管理",tags = "宠物管理")
public class PetsController {

    @Autowired
    PetsService petsService;

    @Value("${imgurl}")
    private String url;

    @PostMapping("pets/add")
    @ResponseBody
    @ApiOperation("添加宠物")
    public CommonResult add(@RequestBody PetsAddVo petsAddVo){

        User user = (User)SecurityUtils.getSubject().getPrincipal();
        Pets pets = new Pets();
        pets.setUserId(user.getUserId());

        BeanUtils.copyProperties(petsAddVo,pets);
       return petsService.addPets(pets);
    }

//    @GetMapping("user/pets/{userId}")
//    @ResponseBody
//    @ApiOperation("查询宠物")
//    public CommonResult show(@PathVariable Integer userId){
//        return petsService.findPetsByUserId(userId);
//    }

    @GetMapping("pets/show")
    @ResponseBody
    @ApiOperation("查询宠物")
    public CommonResult<List<PetsListDto>> show(){

        User user = (User)SecurityUtils.getSubject().getPrincipal();
        List<Pets> allPetsByUserId = petsService.findPetsByUserId(user.getUserId());
        ArrayList<PetsListDto> dtos = new ArrayList<>();
        for (Pets pets : allPetsByUserId){
            PetsListDto petsListDto = new PetsListDto();
            BeanUtils.copyProperties(pets, petsListDto);
            dtos.add(petsListDto);
        }
        return CommonResult.onSuccess(dtos);
    }

    @DeleteMapping("pets/{petId}")
    @ResponseBody
    @ApiOperation("删除宠物")
    public CommonResult delete(@PathVariable Integer petId) {
        return petsService.deletePetsByPetId(petId);
    }

    @PutMapping("pets/{petId}")
    @ResponseBody
    @ApiOperation("编辑宠物信息")
    public CommonResult update(@RequestBody Pets pets){
        return petsService.updatePets(pets);
    }

    @PostMapping("/pets/img/upload")
    @ResponseBody
    @ApiOperation("更改宠物头像")
    public CommonResult imgUpload(MultipartFile file,Integer petId) {

        //生成一个随机字符串,作为新的文件名
        String str = UUID.randomUUID().toString();
        //获取用户上传文件的文件名
        String filename = file.getOriginalFilename();
        //根据最后一个 . 做分割,获取到用户的文件类型
        String split = filename.substring(filename.lastIndexOf("."));

        //创建一个输出流
        FileOutputStream outputStream = null;
        try {
            //将文件保存到nginx
            outputStream = new FileOutputStream("C:/nginx-1.16.1/html/petimg/" + str + split);
            outputStream.write(file.getBytes());
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //关闭流
            try {
                if (outputStream != null) {
                    outputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        //生成的随机字符串+文件名后缀,作为保存在数据库里的新文件名
        String finalImg = str + split;
        /**
         * 域名+文件夹名+图片名
         * url: 最上面的成员变量,加上@value,获取到yml文件里的值
         * userimg/: nginx里的文件夹
         */
        String imgurl = url + "petimg/" + finalImg;
        int row = petsService.upLoadImg(imgurl,petId);
        return row>0 ? CommonResult.onSuccess(ResultStatus.OK):CommonResult.onFailed(ResultStatus.UPDATE_FAILED);
    }

}
